import { Button, message, Modal, Transfer } from 'antd';
import router from 'next/router';
import React, { ReactNode, useEffect, useState } from 'react';
import an58 from '@mmstudio/an000058';
import RightContainer from '../../../components/rightcontainer';
import { Message as M2, Result as R2 } from '../../api/admin/groups/delug.api';
import { Message as M3, Result as R3 } from '../../api/admin/groups/addug.api';
import api from '../../../atoms/api';
import confirm from '../../../atoms/confirm';
import { Query as Q1, Result as R1 } from '../../api/admin/groups/queryu.api';
import TableTransfer from './tabletransfer';

export default function Reluser({
	groupid,
	disabled
}: {
	groupid: string;
	disabled: boolean;
}) {
	//显示隐藏
	const [visible, setvisible] = useState(false);
	const [confirmLoading, setConfirmLoading] = useState(false);
	//查询全部用户，以及已选择用户
	const [data, setdata] = useState([] as ITbfduser[]);
	const [query, setquery] = useState({} as Q1);
	const [selected, setselected] = useState([] as string[]);
	async function reload(q: Q1) {
		q.groupid = groupid;
		setquery(q);
		const data = await an58<R1, Q1>(api['/api/admin/groups/queryu'], 'get', q);
		setdata(data.users);
		setselected(data.selected);
	}
	useEffect(() => {
		void reload(query);
	}, [query]);
	//穿梭框
	return <>
		<div className='e'>
			<Button shape='round' disabled={disabled} type='primary' onClick={() => {
				setvisible(true);
				setquery(query);
				reload(query);
			}}>关联用户</Button>
		</div>
		<Modal
			confirmLoading={confirmLoading}
			title={'关联用户'}
			visible={visible}
			maskClosable
			onCancel={() => {
				if (confirmLoading) {
					return;
				}
				setConfirmLoading(false);
				setvisible(false);
			}}
			footer={null}>
			{/* 穿梭框 */}
			<TableTransfer
				data={data}
				targetKeys={selected}
				onChange={(keys) => {
					setselected(keys);
				}}
			/>
			<RightContainer>
				<Button onClick={async () => {
					const ok = await confirm('关联用户', '确认关联用户');
					if (ok) {
						//删除原有数据
						const res = await an58<R2, M2>(api['/api/admin/groups/delug'], 'delete', {
							groupid
						});
						if (res.ok === true) {
							//新增数据
							const res = await an58<R3, M3>(api['/api/admin/groups/addug'], 'post', {
								groupid, userid: selected
							});
							if (res.ok === true) {
								message.success('关联用户成功');
							} else {
								message.error(res.message);
							}
						} else {
							message.error(res.message);
						}
					}
				}
				}>确定</Button>
				<Button onClick={() => {
					setvisible(false);
				}}>取消</Button>
			</RightContainer>
		</Modal>
		<style jsx>{`
.footer{
	display: flex;
	justify-content: center;
}
.e{
	display: flex;
	justify-content: flex-end;
	align-items: center;
	margin: 0.5rem 0;
}
`}</style>
	</>;
}

